#!/usr/bin/python
# -*- coding: utf-8 -*-
############################################################################
#    Copyright (C) 2010 by Nestor Aguirre                                  #
#    nfaguirre@imaff.cfmac.csic.es                                         #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import os
import sys

PIAMOD_HOME = os.getenv("PIAMOD_HOME")
if( PIAMOD_HOME == None ):
	print "### Error ###: Environment variable PIAMOD_HOME not found !!!"
	quit()
sys.path.append(PIAMOD_HOME+"/src")

from ParserTextBlock import *

class BGrep:
		
	@staticmethod
	def systemOptions():
		output=[]
		previous=""
		current=""
		
		for i in range(1,len(sys.argv)):
			option=""
			value=""
			
			if( re.match( "-{1,2}[\D]+[\d]*", sys.argv[i] ) ):
				option = sys.argv[i]
				
				if( i+1 < len(sys.argv) ):
					if( re.match( "([-]{0,1}[\d]+.[\d]+$|^[\^\w\d\"\(.*\[\\\]+.*$)", sys.argv[i+1] ) ):
						value = sys.argv[i+1]
					else:
						value = None
				else:
					value = None
					
			if( option != "" ):
				output.append( (option,value) )
			
		return output
		
	@staticmethod
	def usage():
		print "Usage:"
		print "   $ bgrep [OPTIONS] FILE"
		print ""
		print "OPTIONS"
		print ""
		print "   -b  regExp"
		print "       Regular expression for matching in the begin of the block"
		print "       (default=\".*\", equivalento to begin of file)"
		print "   -e  regExp"
		print "       Regular expression for matching in the end of the block"
		print "       (default=\"EOF$$\", equivalent to end of file)"
		print "   -f  regExp"
		print "       Regular expression for filter in the end of the block"
		print "       (default=\".*\", equivalent to no filter)"
		print "   -nh"
		print "       Activates the flag to include not the header"
		print "   -nf"
		print "       Activates the flag to include not the footer"
		print "   -p  Integer"
		print "       Extracts a specific block number p>0"
		quit()
		
	@staticmethod
	def main():
		includeHeader = True
		includeFooter = True
		reBegin = ".*"
		reEnd = "EOF$$"
		lineFilter = ".*"
		position = -1
		remove = False
		
		# Se procesan las opciones
		for option in BGrep.systemOptions():
			#print option
			if( option[0] == "-b" ):
				reBegin = option[1]
			elif( option[0] == "-e" ):
				reEnd = option[1]
			elif( option[0] == "-f" ):
				lineFilter = option[1]
			if( option[0] == "-nh" ):
				includeHeader = False
			elif( option[0] == "-nf" ):
				includeFooter = False
			elif( option[0] == "-p" ):
				position = option[1]
				if( int(position) < 1 ):
					print "## ERROR ## The number of block should be greater than zero (-p option)"
					quit()
			elif( option[0] == "-r" ):
				remove = True
			
		# Verifica las opciones obligatorias
		if( sys.argv[-1][-5:] == "bgrep" ):
			BGrep.usage()
			return 0
			
		# Se selecciona la ultima opción para el archivo de entrada
		ifile = file( sys.argv[-1] )
		ifile.close()
		
		if( ifile != None ):
			parser = ParserTextBlock( sys.argv[-1] )
			
			#print "#", reBegin, reEnd, lineFilter, position
			
			parser.extractBlock( reBegin, reEnd, lineFilter )
			
			block = parser.extractBlock( reBegin, reEnd, lineFilter, int(position) )
			
			output = ""
			
			if( includeHeader and len(block.header) > 0 ):
				output += block.header
				
			if( includeHeader and len(block.header) > 0 and len(block.content) > 0 ):
				output += "\n"
				
			if( len(block.content) > 1 ):
				output += block.content
			
			if( includeFooter and len(block.content) > 0 and len(block.footer) > 0 ):
				output += "\n"
			
			if( includeFooter and len(block.footer) > 0 ):
				output += block.footer
			
			print output
			
		#else:
			## Si el archivo no existe, se intenta obtener
			## la información desde entrada estandar
			#ofile = file( ".cin~", "w" )
			#ofile.write( sys.stdin.read(0) )
			#ofile.close()
			
			#parser = ParserTextBlock( ".cin~" )
			#block = parser.extractBlock( reBegin, reEnd, filter )
			#if( block.content != "" ):
				#output = ""
				
				#output += block.header+"\n"
				#output += block.content+"\n"
				#output += block.footer
				
				#print output
				
if __name__ == "__main__":
	BGrep.main()
